package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.BoardMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Board;
import com.example.forum.services.IBoradService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class BoardServiceImpl implements IBoradService {
    @Autowired
    private BoardMapper boardMapper;
    @Override
    public List<Board> selectByNum(Integer num) {
        if(num<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        List<Board> boards = boardMapper.selectByNum(num);
        return boards;


    }

    @Override
    public void addOnceArticleCountById(Long id) {          //
        if(id==null||id<=0){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));

        }
        Board result = boardMapper.selectByPrimaryKey(id);

        Board board = new Board();
        board.setId(id);
        board.setArticleCount(result.getArticleCount()+1);
        boardMapper.updateByPrimaryKeySelective(board);


    }

    @Override
    public Board selectById(Long id) {
        if(id==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed("参数校验失败"));
        }
        Board board = boardMapper.selectByPrimaryKey(id);
        return board;
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed("参数校验失败"));
        }
        Board result = boardMapper.selectByPrimaryKey(id);
        if(result==null||result.getDeleteState()==1||result.getState()==1){
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));

        }

        Board board = new Board();
        board.setId(id);
        board.setArticleCount(result.getArticleCount()-1);
        //如果小于零，就设置为0
        if(board.getArticleCount()<0){
            board.setArticleCount(0);
        }
        boardMapper.updateByPrimaryKeySelective(board);

    }
}
